<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px" class="queryForms">
			<el-form-item label="器材名称" prop="deviceName">
				<el-input v-model="queryParams.deviceName" placeholder="请输入器材名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="件号" prop="partNumber">
				<el-input v-model="queryParams.partNumber" placeholder="请输入件号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="申请人" prop="createBy">
				<el-input v-model="queryParams.createBy" placeholder="请输入申请人" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="状态" prop="inspectStatus">
				<el-select v-model="queryParams.inspectStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.inspect_status" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="申请日期" prop="applyTime">
				<el-date-picker v-model="queryParams.applyTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择申请日期"> </el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['synthesize:sentrance:exam']">送检</el-button>
			</el-col>
			<!-- <el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleIn" v-hasPermi="['synthesize:sentrance:in']">入库</el-button>
			</el-col> -->
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleBack" v-hasPermi="['synthesize:sentrance:back']">退货</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDown" v-hasPermi="['synthesize:sentrance:issue']">下发</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="entrance57" :showSearch.sync="showSearch" @queryTable="handleQuery" :columns.sync="columns" perm="synthesize:store:entrance"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<!-- lazy :load="loadListDes" -->
			<el-table :row-class-name="row_class_name" @mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter" @cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable" ref="table" v-loading="loading" :data="EntranceList" @selection-change="handleSelectionChange" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"  border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
						</template
					>
				</el-table-column>
				<el-table-column label="编号" prop="number" min-width="150" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="申请单编号" prop="recordNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="申请日期" prop="applyTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />

				<el-table-column label="要求完成日期" prop="completeTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="器材名称" prop="deviceName" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="状态" prop="inspectStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[10].visible">
					<template slot-scope="scope">
						<!-- <dict-tag :options="dict.type.inspect_status" :value="scope.row.inspectStatus" /> -->

            <el-tag type="warning"   v-if="scope.row.inspectStatus == '0' || scope.row.inspectStatus == '1'
            || scope.row.inspectStatus == '7'">{{ scope.row.inspectStatus == '0'?"待入库":scope.row.inspectStatus == '1'?'已入库':'待质检' }}</el-tag>
             <el-tag type="success"   v-if="scope.row.inspectStatus == '3' || scope.row.inspectStatus == '5'
            || scope.row.inspectStatus == '6'">{{ scope.row.inspectStatus == '3'?"合格":scope.row.inspectStatus == '5'?'让步接收':'已下发' }}</el-tag>
             <el-tag type="danger"  v-if="scope.row.inspectStatus == '2' || scope.row.inspectStatus == '4'">{{ scope.row.inspectStatus == '2'?"退货":'不合格' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="件号" prop="partNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="数量" prop="num" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<el-table-column label="技术要求" prop="demand" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="用途" prop="purpose" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible" />
				<el-table-column label="申请人" prop="createBy" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="器材接收人" prop="recipientName" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="器材接收时间" prop="recipientTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />

				<el-table-column label="操作" class-name="small-padding fixed-width" width="122px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildrens">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['synthesize:sentrance:annex']">附件</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['synthesize:sentrance:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination62" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改发票对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" class="add-form1" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="供方" prop="supplier">
					<el-input v-model="form.supplier" placeholder="请输入供方" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="时间" prop="inspectTime">
					<el-date-picker v-model="form.inspectTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择时间"> </el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 下发 -->
		<el-dialog title="下发" :visible.sync="isssueOpen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="issueForm" class="add-form1" :model="issueForm" :rules="issueRules" label-width="80px">
				<el-form-item label="接收人" prop="recipientId">
					<el-select v-model="issueForm.recipientId" placeholder="请选择接收人" filterable @change="changeUser()">
						<el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
					</el-select>
				</el-form-item>
				<el-form-item label="接收时间" prop="recipientTime">
					<el-date-picker v-model="issueForm.recipientTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择接收时间"> </el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="issueSubmitForm">确 定</el-button>
				<el-button @click="issueCancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listEntrance, listEntranceChild, submitEntrance, delEntrance, handleEntranceIn, handleEntranceBack, handleEntranceDown, productionApprove, getPlanData, editEntrancePlan } from "@/api/synthesize/store/entrance"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import ProductPlan from "@/views/components/ProductPlan"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import CreateForm from "@/views/components/CreateForm"
import { mapGetters } from "vuex"
import { getUserList,getcolumn } from "@/api/selectList"

export default {
	name: "Entrance",
	dicts: ["default_approve", "product_intact_state", "inspect_status"],
	components: { ApproveTemplete, ProductPlan, RecordsTemplete, CreateForm },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			EntranceList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				deviceName: undefined,
				inspectStatus: undefined,
				applyTime: undefined,
				partNumber: undefined,
				createBy: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				supplier: [{ required: true, message: "请输入供方", trigger: "blur" }],
				inspectTime: [{ required: true, message: "请输入时间", trigger: "blur" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 生产计划
			isOne: false,
			disabled: false,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `编号`, visible: true },
				{ key: 1, label: `申请单编号`, visible: true },
				{ key: 2, label: `申请日期`, visible: true },
				{ key: 3, label: `要求完成日期`, visible: true },
				{ key: 4, label: `器材名称`, visible: true },
				{ key: 5, label: `件号`, visible: true },
				{ key: 6, label: `数量`, visible: true },
				{ key: 7, label: `技术要求`, visible: true },
				{ key: 8, label: `用途`, visible: true },
				{ key: 9, label: `申请人`, visible: true },
				{ key: 10, label: `状态`, visible: true }
			],
			// 下发
			isssueOpen: false,
			issueForm: {},
			issueRules: {
				recipientId: [{ required: true, message: "请选择接收人", trigger: "change" }],
				recipientTime: [{ required: true, message: "请选择接收时间", trigger: "blur" }]
			},
			userList: []
		}
	},
	created() {
		this.getUserList()
		this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		this.getUserList()
		this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
    getSize() {
			getcolumn({ pageName: "Pagination62" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		// 获取用户下拉列表
		async getUserList() {
			let ret = await getUserList()
			this.userList = ret.rows
		},
		// 更改用户
		changeUser() {
			let cur = this.userList.find(ele => {
				return ele.userId == this.issueForm.recipientId
			})
			this.issueForm.recipientName = cur.nickName
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listEntrance(this.queryParams).then(response => {
				response.rows.forEach((item, index) => {
					item.hasChildrens = true
					item.sort = index + 1
          this.$refs.table.toggleRowExpansion(item, false);
					item.children.forEach((items, indexs) => {
						items.sort = indexs + 1
						items.hasChildrens = false
						items.id = "c" + items.id
					})
				})
				this.EntranceList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, {
					treeNode,
					resolve
				})
			}
			let data = {
				id: tree.id,
				deviceName: this.queryParams.deviceName,
				inspectStatus: this.queryParams.inspectStatus,
				applyTime: this.queryParams.applyTime,
				partNumber: this.queryParams.partNumber,
				createBy: this.queryParams.createBy
			}
			let ret = await listEntranceChild(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.$refs.table.clearSelection()
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				ids: undefined,
				supplier: undefined,
				inspectTime: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
			this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
				let flag = this.ids.some(item => item == row.id)
				if (row.hasChildrens) {
					row.children.forEach(items => {
						if (flag) {
							this.$refs.table.toggleRowSelection(items, true)
						}
					})
				}
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		checkIds() {
			// 判断ids
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			return ids
		},
		// 更新树
		refreshTree() {
			this.rows = []
			this.ids = []
			// 这个刷新checkbox有问题
			this.treeMap.forEach((item, idx) => {
				this.loadListDes({ id: idx }, item.treeNode, item.resolve)
			})
			// this.treetablekey = Math.random()
		},
		/** 送检操作 */
		handleAdd() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus == "0" || item.inspectStatus == "2") {
					checkrows = true
				}
			})
			if (!checkrows) {
				this.$modal.msg("只有未入库和已退货可以送检")
				return false
			}
			this.reset()
			this.form.ids = ids
			this.open = true
			this.title = "送检"
		},
		// 入库
		handleIn() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "0" && item.inspectStatus != "2") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有待入库和退货可以入库")
				return false
			}
			this.$modal
				.confirm("是否确认入库数据项？")
				.then(function () {
					return handleEntranceIn(ids)
				})
				.then(() => {
					this.$modal.msgSuccess("入库成功")
					// this.refreshTree()
					this.getList()
				})
				.catch(() => {})
		},
		// 退货
		handleBack() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			this.rows.forEach(item => {
				if (item.inspectStatus != "1" && item.inspectStatus != "4") {
					checkrows = true
				}
			})
			if (checkrows) {
				this.$modal.msg("只有入库和不合格可以退货")
				return false
			}
			// 退货操作
			this.$modal
				.confirm("是否确认退货数据项？")
				.then(function () {
					return handleEntranceBack(ids)
				})
				.then(() => {
					// this.refreshTree()
					this.getList()
					this.$modal.msgSuccess("退货成功")
				})
				.catch(() => {})
		},
		// 下发
		handleDown() {
			let ids = this.checkIds()
			if (!ids) {
				return false
			}
			// 判断状态
			let checkrows = false
			// this.rows.forEach(item => {
			// 	if (item.inspectStatus != "1" && item.inspectStatus != "3" && item.inspectStatus != "5") {
			// 		checkrows = true
			// 	}
			// })
			// if (checkrows) {
			// 	this.$modal.msg("只有入库、合格、让步接收可以下发")
			// 	return false
			// }
			this.issueForm = {
				ids: ids,
				recipientId: undefined,
				recipientName: undefined,
				recipientTime: undefined
			}
			this.resetForm("issueform")
			this.isssueOpen = true
		},
		// 下发提交
		issueSubmitForm() {
			this.$refs["issueForm"].validate(valid => {
				if (valid) {
					handleEntranceDown(this.issueForm).then(response => {
						// this.refreshTree()
						this.$refs.table.clearSelection()
						this.$modal.msgSuccess("下发成功")
						this.isssueOpen = false
						this.getList()
					})
				}
			})
		},
		issueCancel() {
			this.$refs.table.clearSelection()
			this.isssueOpen = false
		},
		/** 修改按钮操作 */
		// handleUpdate(row) {
		//   this.reset();
		//   const id = row.id || this.ids;
		//   getEntrance(id).then((response) => {
		//     this.form = response.data;
		//     this.open = true;
		//     this.title = "修改设备保养计划";
		//   });
		// },
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					submitEntrance(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.getList()
						// this.treetablekey = Math.random()
						// this.treeMap.forEach((item, idx) => {
						// 	this.loadListDes({ id: idx }, item.treeNode, item.resolve)
						// })
					})
				}
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delEntrance(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id,
				workflowType: "5"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		// 关闭更改保养计划
		cancelChange() {
			this.changeOpen = false
		},
		// 工艺流程列表
		showTechnologyList() {
			return false
			alert("工艺流程列表")
		},
		// 附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 43,
					perm: "synthesize:sentrance:annex"
				}
			})
		},
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 44,
					perm: "synthesize:sentrance:annex2"
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 122px !important;
}
</style>
